from llms.zhipu import chat

from prompts.init_interview import GENERATE_QUESTION_PROMPT, RESUME_SUMMARY_PROMPT, JD_INO_EXTRACT
from mapper.interview_question import query_questions_by_company_and_position
from utils.parse_utils import parse_markdown_json_content


# 辅助函数：生成 "个人信息摘要"
async def generate_summary(job_description: str, resume_text: str) -> str:
    # 拼接 Prompt 让 LLM 生成个人信息摘要
    prompt = RESUME_SUMMARY_PROMPT.format(job_description=job_description, resume_text=resume_text)

    # 调用 zhipuAI 接口生成摘要
    response = chat([{"role": "user", "content": prompt}])
    summary = response.strip()
    return summary


# 辅助函数：生成 "待提问问题"
async def generate_questions(job_description: str, resume_text: str):
    # 查询参考问题
    reference_questions, company, job_position = query_reference_questions(job_description)
    # 拼接 Prompt 让 LLM 生成问题
    prompt = GENERATE_QUESTION_PROMPT.format(job_description=job_description, resume_text=resume_text,
                                             reference_questions=reference_questions)

    # 调用 OpenAI 接口生成问题
    response = chat([{"role": "user", "content": prompt}])
    questions = response.strip()
    return {'questions': questions, 'company': company, 'job_position': job_position}


def parse_job_description(job_description):
    prompt = JD_INO_EXTRACT.format(job_description=job_description)
    response = chat([{"role": "user", "content": prompt}])
    return parse_markdown_json_content(response)


def query_reference_questions(job_description: str):
    # 查询参考问题
    company, job_position = parse_job_description(job_description)
    questions = query_questions_by_company_and_position(company, job_position=job_position)
    reference_questions = get_top_questions_as_string(questions=questions)
    return reference_questions, company, job_position


def get_top_questions_as_string(questions, top_n=10):
    """
    从查询结果中提取前 N 个问题，并拼接为换行符分隔的字符串。
    :param questions: 查询返回的 InterviewQuestion 对象列表
    :param top_n: 需要提取的问题数量，默认是前 10 个
    :return: 以换行符分隔的字符串，包含前 N 个问题的内容
    """
    # 获取前 N 个问题文本（question 字段）
    top_questions = [question.question for question in questions[:top_n]]

    # 使用换行符拼接为字符串
    return "\n".join(top_questions)
